<template>
  <div>
    <!-- 上传图片组件 -->
    <el-upload
      action="action"
      :on-change="uploadChange"
      :file-list="fileList"
      list-type="picture-card"
      :http-request="upload"
      :on-preview="lookBigImg"
      :on-remove="removeImg"
      :limit="limit"
      :on-exceed="fn"
      :class="{exceed: limit === fileList.length}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!--显示大图 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDd7VjkcaDj132ta0Bvb6PuFNK6iAapwuf',
  SecretKey: 'f7OWTVN4au21wfCYkliT4T9du0ucCjfR'
})
export default {
  name: 'UploadImg',
  components: {},
  props: {
    // imgUrl: {
    //   type: String,
    //   required: true
    // }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      limit: 1
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    initImgUrl(url) {
      if (!url) return
      this.fileList = [{ url }]
    },
    fn() {
      alert('您已超出上传图片个数限制')
    },
    removeImg(file) {
      // console.log(file)
      this.$emit('uploadSuccess', '')
    },
    lookBigImg(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    uploadChange(file, fileList) {
      // console.log(fileList) // 1
      // console.log(this.fileList) // 0
      this.fileList = fileList
    },
    // 手动上传图片的函数
    upload(file) {
      // const index = file.file.name.lastIndexOf('.')
      // const ext = file.file.name.slice(index)
      const upload_img = this.fileList.find(item => item.uid === file.file.uid)

      upload_img.status = 'uploading'
      upload_img.percentage = 0

      const index = upload_img.name.lastIndexOf('.')
      const ext = upload_img.name.slice(index)
      cos.uploadFile({
        Bucket: 'dyy-01-1317543627', /* 填写自己的 bucket，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        // Key: '1.jpg', /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        // Date.now() 得到的是一个时间戳，目的：得到一个唯一值
        Key: String(Date.now()) + String(Number.parseInt(Math.random() * 1000000000)) + ext,
        /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        // Body: file.file, // 上传文件对象
        Body: upload_img.raw, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function(progressData) {
          // console.log(JSON.stringify(progressData))
          upload_img.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
          upload_img.status = 'fail'
        } else {
          console.log('上传成功')
          console.log(data)
          upload_img.status = 'success'
          const img_url = 'http://' + data.Location
          this.$emit('uploadSuccess', img_url)
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .exceed {
    .el-upload--picture-card {
      display: none !important;
    }
  }
}
</style>
